package com.mars.push.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mars.push.core.request.PushRequest;
import com.mars.push.core.service.PushService;
import com.turo.pushy.apns.*;
import com.turo.pushy.apns.util.SimpleApnsPushNotification;
import com.turo.pushy.apns.util.concurrent.PushNotificationFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @author wq
 * @version 1.0
 * @date 2021/03/04 15:46
 */
@Service
@Slf4j
public class IosPushImpl implements PushService {


    @Value("${push.ios.certPassword}")
    private String certPassword;

    @Value("${push.ios.certFile}")
    private String certFile;


    @Override
    public boolean singlePush(PushRequest req) {
        JSONObject data = new JSONObject();
        JSONObject aps = new JSONObject();
        JSONObject alert = new JSONObject();
        alert.put("title", req.getTitle());
        alert.put("body", req.getContent());
        aps.put("alert", alert);
        data.put("aps", aps);
        data.put("extras", req.getExtras());
        String topic = "com.imlianka.lkapp";
        String payload = data.toJSONString();
        //有效时间
        Date invalidationTime = new Date(System.currentTimeMillis() + 60 * 60 * 1000L);
        //发送策略 apns-priority 10为立即 5为省电
        DeliveryPriority priority = DeliveryPriority.IMMEDIATE;
        //推送的合并ID，相同的 apns-collapse-id会在App中合并
        String collapseId = UUID.randomUUID().toString();
        //apnsId 唯一标示，如果不传，APNs会给我们生成一个
        UUID apnsId = UUID.randomUUID();
        //构造一个APNs的推送消息实体
        SimpleApnsPushNotification msg = new SimpleApnsPushNotification(req.getRegisterId(), topic, payload, invalidationTime, priority, PushType.ALERT, collapseId, apnsId);
        ApnsClient client = client();
        if (client != null) {
            PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> future = client.sendNotification(msg);
            try {
                PushNotificationResponse<SimpleApnsPushNotification> response = future.get();
                System.out.println("ios  server response ===>" + JSONObject.toJSONString(response));
                return true;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public String getAccessToken() throws Exception {
        return null;
    }


    private ApnsClient client() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
        URL url = this.getClass().getClassLoader().getResource( certFile);
        if (url != null) {
            try {
                File cert = new File(url.getPath());
                return new ApnsClientBuilder()
                        .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
                        .setClientCredentials(cert, certPassword)
                        .setConcurrentConnections(4)
                        .setEventLoopGroup(eventLoopGroup)
                        .build();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
